#include "C_SingleApplication.h"
#include <QtNetwork/QLocalSocket>
#include <QFileInfo>

#define TIME_OUT                (500)    // 500ms

C_SingleApplication::C_SingleApplication(int &argc, char **argv)
    : QApplication(argc, argv)
    , m_bRunning(false)
    , m_widget(NULL)
    , m_localServer(NULL)
{
    m_strServerName = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
    InitLocalConnection();
}

C_SingleApplication::~C_SingleApplication()
{
    if (m_localServer)
    {
        m_localServer->close();
        m_localServer->deleteLater();
    }
}

bool C_SingleApplication::IsRunning()
{
    return m_bRunning;
}

void C_SingleApplication::SetWidget(QWidget *widget)
{
    m_widget = widget;
}

void C_SingleApplication::NewLocalConnection()
{
    QLocalSocket *socket = m_localServer->nextPendingConnection();
    if(socket)
    {
        socket->waitForReadyRead(2*TIME_OUT);
        delete socket;

        if(m_widget)
        {
            emit newLocalConnection();
        }
    }
}

void C_SingleApplication::InitLocalConnection()
{
    m_bRunning = false;

    QLocalSocket socket;
    socket.connectToServer(m_strServerName);

    if(socket.waitForConnected(TIME_OUT))
    {
        qDebug() << m_strServerName
                 << " already running."
                 << endl;

        m_bRunning = true;

        return;
    }

    NewLocalServer();
}

void C_SingleApplication::NewLocalServer()
{
    m_localServer = new QLocalServer(this);
    connect(m_localServer, SIGNAL(newConnection()),
            this, SLOT(NewLocalConnection()));

    if( ! m_localServer->listen(m_strServerName))
    {
        if(m_localServer->serverError() == QAbstractSocket::AddressInUseError)
        {
            QLocalServer::removeServer(m_strServerName);
            m_localServer->listen(m_strServerName);
        }
    }
}
